package edu.mit.simile.longwell.login;

import it.okkam.webid.model.DataModel;

import java.io.*;
import javax.servlet.*;
import org.apache.log4j.Logger;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.util.FileManager;

import edu.mit.simile.longwell.LongwellServer;

public class CheckLogin {
	final static private Logger s_logger = Logger.getLogger(CheckLogin.class);
	protected static ServletContext context;
/**
 * get user name and password from the user rdf store
 */
	public static boolean check(String userName, String password , String fileName) {
		
		Model model = null;
		
		boolean valid = false;
		
		InputStream in = FileManager.get().open(fileName);
		if (in == null) {		    
			System.out.println("File Not Found");
		}
		else {
		// Create the input model. Models different from the default one import also the 
		// rdf and rdf-schema axioms. The input model usually comes with blank nodes. 
			//model = ModelFactory.createDefaultModel();	
		// read the RDF/TURTLE file
			//model.read(in, null, "TURTLE");
			//model = LongwellServer.getBCCDataset().getDefaultModel();
			//carico gli utenti dal grafo e non dal default model
			model = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");
			
		}
		if(model != null){
			Property prop = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
			RDFNode pred = model.createResource("http://xmlns.com/foaf/0.1#Person");
			
			String prefix = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
							"PREFIX xfoaf:   <http://www.foafrealm.corrib.org/xfoaf/0.1/> " +
							"PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> " +
							"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ";
			//check webid if it is in the rivela user group
			String queryString = prefix + '\n'
				+ "ask { :rivela_user foaf:member :"+ userName +" . " +
						":"+ userName +" foaf:nickname \""+userName +"\". " +
						":"+ userName +" xfoaf:password_sha1sum \""+DataModel.generateHash(password) +"\" " +	". } ";
			
			//System.out.println(queryString);
			
			Query query = QueryFactory.create(queryString) ;
			QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
			
			valid = qexec.execAsk() ;
			
			qexec.close() ;
		}
		
		return valid;
	
	}
}